package com.hxkj.service.taglib.impl;

import com.alibaba.fastjson.JSONObject;
import com.hxkj.client.service.AnalyzeTagsServiceClient;
import com.hxkj.client.service.ArticleServiceClient;
import com.hxkj.client.service.TagsServiceClient;
import com.hxkj.client.service.UniversalServiceClient;
import com.hxkj.domain.enums.TagsExceptionEnum;
import com.hxkj.domain.po.*;
import com.hxkj.service.taglib.AnalyzeTagsService;
import com.hxkj.token.utils.TokenUtils;
import com.platform.common.domain.exception.CustomException;
import com.platform.common.domain.exception.CustomMessageException;
import com.platform.common.domain.result.ParameterDataStruct;
import com.platform.common.domain.result.ResultDataStruct;
import com.platform.common.domain.result.ResultPageStruct;
import com.platform.common.domain.to.PageTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.hxkj.domain.Constant.CmsConstants.TAGSDEATIL;

/**
 * @ClassName AnalyzeTagsServiceImpl
 * @Description TODO
 * @Author Mr.zheng
 * @Date 2018/7/20 17:18
 * @Version 1.0
 */
@Service
@Slf4j
public class AnalyzeTagsServiceImpl implements AnalyzeTagsService {
    @Autowired
    private UniversalServiceClient universalServiceClient;

    @Autowired
    private AnalyzeTagsServiceClient analyzeTagsServiceClient;

    @Autowired
    private ArticleServiceClient articleServiceClient;

    @Autowired
    private TagsServiceClient tagsServiceClient;

    @Autowired
    private TokenUtils tokenUtils;

    @Override
    public JSONObject analyzeTags(FreeMarker freeMarker) throws Exception {
        try {
            AuthUser auser = (AuthUser) tokenUtils.getTokenUserInfo();
            freeMarker.setUserToken(String.valueOf(auser.getUserId()));
            //Mr.zheng:获取站点信息中的模板
            SiteUniversal siteUniversal = new SiteUniversal();
            siteUniversal.setSiteId(freeMarker.getSiteId());
            siteUniversal = universalServiceClient.get(siteUniversal).getData();

            if (siteUniversal.getTagsTempletId() == null) {
                throw new CustomMessageException(402, "站点设置未绑定模板;请重新绑定!");
            }
            freeMarker.setTempletId(siteUniversal.getTagsTempletId());
            // 静态文件生成时需要同时传递pc端模板id和wap端模板id
            freeMarker.setWapTempletId(siteUniversal.getmTempletId());
            freeMarker.setAliasName("tags");
            freeMarker.setChannelId("0");
            freeMarker.setSiteId(siteUniversal.getSiteId());

            ResultDataStruct resultDataStruct = analyzeTagsServiceClient.analyzeTags(freeMarker);
            if (resultDataStruct.getCode() != 200 ) {
                throw new CustomMessageException(resultDataStruct.getCode(), "tag聚合模板解析失败！错误信息：" + resultDataStruct.getMessage());
            }
            return (JSONObject) resultDataStruct.getData();
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 标签模板可视化,标签模板每个站点共用一个模板
     * @param freeMarker
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject visualizationTags(FreeMarker freeMarker) throws Exception {
        try {
            if(freeMarker.getTempletId() == null){
                // 因为每个站点标签模板共用一个模板,这里是直接通过站点id获取站点信息来获取的模板id,
                // 但如果前端不传模板id过来,这里无法判断是PC端模板可是化还是Wap端模板可视化,所以加一个非空校验
                throw new CustomMessageException(400, "可视化时模板ID不能为空");
            }
            Tags tags = new Tags();
            tags.setSiteId(freeMarker.getSiteId());
            List<Tags> tagsList = tagsServiceClient.getShowTagsList(tags);
            if (tagsList == null || tagsList.size() == 0) {
                throw new CustomMessageException(401, "没有可供选择的tags");
            }
            tags = tagsList.get(0);
            freeMarker.setTagsId(tags.getTagsId());

            AuthUser auser = (AuthUser) tokenUtils.getTokenUserInfo();
            freeMarker.setUserToken(String.valueOf(auser.getUserId()));
            //Mr.zheng:获取站点信息中的模板
            SiteUniversal siteUniversal = new SiteUniversal();
            siteUniversal.setSiteId(freeMarker.getSiteId());
            ResultDataStruct<SiteUniversal> siteResult = universalServiceClient.get(siteUniversal);
            if (siteResult.getCode() != 200 ) {
                throw new CustomMessageException(siteResult.getCode(), siteResult.getMessage());
            }
            siteUniversal = siteResult.getData();
            if (siteUniversal.getTagsTempletId() == null) {
                throw new CustomMessageException(402, "站点设置未绑定模板;请重新绑定!");
            }
            // 如果可视化模板是wap端模板, 将wap模板id设到templetId上,可视化时都是通过templetId来取模板内容
            if(freeMarker.getTempletId().equals(siteUniversal.getmTempletId())){
                freeMarker.setTempletId(siteUniversal.getmTempletId());
            }else {
                freeMarker.setTempletId(siteUniversal.getTagsTempletId());
            }
            freeMarker.setAliasName("tags");
            freeMarker.setChannelId("0");
            freeMarker.setSiteId(siteUniversal.getSiteId());

            ResultDataStruct resultDataStruct = analyzeTagsServiceClient.analyzeTags(freeMarker);
            if (resultDataStruct.getCode() != 200 ) {
                throw new CustomMessageException(resultDataStruct.getCode(), "tag聚合模板解析失败！错误信息：" + resultDataStruct.getMessage());
            }
            return (JSONObject) resultDataStruct.getData();
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public JSONObject analyzeTagArticle(FreeMarker freeMarker) throws Exception {
        try {
            AuthUser auser = (AuthUser) tokenUtils.getTokenUserInfo();
            freeMarker.setUserToken(String.valueOf(auser.getUserId()));
            //Mr.zheng:获取站点信息中的模板
            SiteUniversal siteUniversal = new SiteUniversal();
            siteUniversal.setSiteId(freeMarker.getSiteId());
            siteUniversal = universalServiceClient.get(siteUniversal).getData();

            if (siteUniversal.getTagsTempletId() == null) {
                throw new CustomException(TagsExceptionEnum.TAGS_TAGTEMPLET_NOT_EXIST);
            }
            freeMarker.setTempletId(siteUniversal.getTagsTempletId());
            // 静态文件生成时需要同时传递pc端模板id和wap端模板id
            freeMarker.setWapTempletId(siteUniversal.getmTempletId());
            Tags tags = new Tags();
            tags.setSiteId(freeMarker.getSiteId());
            tags.setTagsId(freeMarker.getTagsId());
            return getAnalyzePathByTags(freeMarker, tags);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * @author Mr.zheng
     * @Description getAnalyzePath 异步生成静态地址并存储
     * @Date 14:02 2018/8/23
     **/
    @Async
    protected JSONObject getAnalyzePathByTags(FreeMarker freeMarker, Tags tags) throws Exception {
        PageTo pageTo = getArticleResultPageStructByTags(tags);
        ResultDataStruct resultDataStruct;
        JSONObject jsonObject = null;
        int i = 1;
        do {
            //生成tag详情页
            freeMarker.setAliasName("tag");
            freeMarker.setTagsId(tags.getTagsId());
            freeMarker.setTime(tags.getCreateTime());
            freeMarker.setStatus(TAGSDEATIL);//6标识tags详情
            freeMarker.setChannelId("-1");
            freeMarker.setPageNum(i);//分页当前页数
            resultDataStruct = analyzeTagsServiceClient.analyzeTagArticle(freeMarker);
            if (resultDataStruct.getCode() != 200) {
                throw new CustomMessageException(resultDataStruct.getCode(), "tag详情模板解析失败！错误信息：" + resultDataStruct.getMessage());
            }
            if (i == 1 && freeMarker.getNote() == null) {
                jsonObject = (JSONObject) resultDataStruct.getData();
                tags.setManuscriptPath("/" + jsonObject.getString("filePath"));
                tagsServiceClient.modifyTags(tags);
            }
            i++;
        } while (i <= pageTo.getPages() && freeMarker.getNote() == null);

        //将每次生成该tag的静态资源则更新到数据库
        return jsonObject;
    }

    private PageTo getArticleResultPageStructByTags(Tags tags) throws Exception {
        PageTo pageParam = new PageTo();
        pageParam.setPageNum(1);
        pageParam.setPageSize(10);

        Article article = new Article();
        article.setTagsId(tags.getTagsId());
        article.setSiteId(tags.getSiteId());
        article.setAuditType(0);
        article.setDelTag(0);

        ParameterDataStruct<Article> parameterDataStruct = new ParameterDataStruct<>();
        parameterDataStruct.setData(article);
        parameterDataStruct.setPageTo(pageParam);
        ResultPageStruct resultPageStruct = articleServiceClient.getArticleListByTags(parameterDataStruct);
        return resultPageStruct.getPageInfo();
    }
}
